package pt.compflow.client;

import java.util.Iterator;

import org.restlet.data.Method;
import org.restlet.engine.header.Header;
import org.restlet.resource.ServerResource;
import org.restlet.util.Series;

import pt.compflow.Context;
import pt.compflow.flowontology.model.FLOWO;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.InternalGroupMembership;
import pt.compflow.flowontology.model.Person;

public abstract class BaseResource extends ServerResource {
	
	//	private static final Logger LOG = LoggerFactory.getLogger(BaseResource.class);
	public static final String LOCAL_GROUP_URI = FLOWO.getURI() + "localGroup";
	public static final String ADMIN_LOCAL_GROUP_URI = FLOWO.getURI() + "adminLocalGroup";
		
	protected Context getCompFlowContext() {
		return ((EngineApplication) getApplication()).getCompFlowContext();
	}
	
	protected Person getPerson(FlowOntologyModel model, String key) {
		return getPerson(model, key, false);
	}
	
	protected Person getPerson(FlowOntologyModel model, String key, boolean mustBeAdmin) {
		Person person = null;
		
		String[] keys = null;
		if(key != null) {
			keys = new String[1];
			keys[0] = key;
		} else {
			keys = getCookies().getValuesArray("k");
		}
		
		if(keys == null) return null;
				
		Iterator<InternalGroupMembership> it = model.listInternalGroupMemberships();
		while(person == null && it.hasNext()) {
			InternalGroupMembership m = it.next();
			if(m.getHasKey(null) != null) for(int i=0;i<keys.length && person == null; i++) if(m.getHasKey(null).compareTo(keys[i]) == 0)
				person = m.getHasPersonPerson();
		}
		
		return person;			
	}
	
	protected Method getMethodOverride() {
		@SuppressWarnings("unchecked")
		Series<Header> headerAttr = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers");
		String value = headerAttr.getFirstValue("X-HTTP-Method-Override");
	
		if(value != null) {
			if(value.compareToIgnoreCase("get") == 0)
				return Method.GET;
			else if(value.compareToIgnoreCase("put") == 0)
				return Method.PUT;
			else if(value.compareToIgnoreCase("delete") == 0)
				return Method.DELETE;				
		}	
			
		return Method.POST;
	}
	
}
